<?php

function app()
{
    return Application::getInstance();
}

final class Application
{
    private static $instance = null;

    public static final function getInstance()
    {
        return self::$instance instanceof self ? self::$instance : (self::$instance = new self);
    }

    private function __construct()
    {
        $this->init();
    }

    public function run()
    {
        echo (string) new Db_Mysql_Table('PRE.sage') . '<br>';
        echo (string) new Db_Mysql_Table(array('someAlias' => 'PRE.sage')) . '<br>';
        echo (string) new Db_Mysql_Table(array('someAlias' => 'sage')) . '<br>';
        echo (string) new Db_Mysql_Table(array('sage'));
        return $this;
    }

    protected function init()
    {
        $this->initAutoload();
    }

    protected function initAutoload()
    {
        spl_autoload_register(array($this, 'autoload'));
    }

    public function autoload($class)
    {
        $classFile = str_replace(' ', DS, ucwords(str_replace('_', ' ', $class)));
        $classFile .= '.php';

        foreach ($this->getIncludePaths() as $path)
        {
            $filename = BP . $path . $classFile;
            if (is_file($filename))
            {
                if (is_readable($filename))
                {
                    require_once $filename;
                    break;
                }
                else
                {
                    self::throwException($this->__('Class file "%s" found, but not readable.', $s));
                }
            }
        }
    }

    protected function getIncludePaths()
    {
        return array(
            'app' . DS . 'core' . DS,
            'app' . DS . 'local' . DS,
        );
    }

    public static function throwException($message = null, $code = null)
    {
        throw new Exception($message, $code);
    }

    public function __()
    {
        $args = func_get_args();
        return $args[1]; // TODO: write translator
    }

    public function getDbConfig()
    {
        return new Config_Db();
    }

    public function db()
    {
        return Db_Mysql_Mysqli::getInstance();
    }
}